import { merge, find } from 'lodash-es';

export class MassMarkerLayer {
  constructor(map, option = {}) {
    const opt = {
      zIndex: 5,
      opacity: 1,
      zooms: [3, 20],
      cursor: 'pointer',
      alwaysRender: false,
    };
    this.map = map;
    this.option = merge(opt, option);
    this.createLayer();
  }
  createLayer() {
    if (!this.layer) {
      this.layer = new AMap.MassMarks([], this.option);
      this.layer.setMap(this.map);
    }
  }
  clearLayer() {
    this.layer.clear();
  }
  getStyle(index) {
    if (typeof index === 'number') {
      return find(this.layer.getStyle(), (val, inx) => inx === index);
    }
    return this.layer.getStyle();
  }
  setStyle(index, style = {}) {
    /* index没传的时候 */
    if (typeof index !== 'number') {
      style = index;
      index = 0;
    }
    const getFormatStyle = (style) => {
      /* style: {url: "",size: new AMap.Size(38, 56),anchor: new AMap.Pixel(0, 0),rotation: 0} */
      style = merge({ size: new AMap.Size(38, 56) }, style);
      if (!style.anchor) {
        const { width, height } = style.size;
        style.anchor = new AMap.Pixel(-1 * (width / 2), -1 * height);
      }
      return style;
    };
    if (Array.isArray(style)) {
      this.layer.setStyle(style.map((item) => getFormatStyle(item)));
    } else {
      const styles = this.getStyle();
      styles[index] = getFormatStyle(style);
      this.layer.setStyle(styles);
    }
  }
  getData(predicate) {
    if (typeof predicate === 'function') {
      return find(this.layer.getData(), predicate);
    }
    return this.layer.getData();
  }
  setData(list = []) {
    this.layer.setData(list);
  }
  destroy() {
    this.clearLayer();
    this.layer.setMap(null);
  }
}
